import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = () => {
  return {
    token: getToken() || null,
    UserInfo: {}
  }
}

const mutations = {
  // 获取token
  getToken(state, newToken) {
    state.token = newToken
    // 放入Cookie中持续储存
    setToken(newToken)
  },
  // 清除token
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 获取用户信息
  getUserInfo(state, UserInfo) {
    state.UserInfo = UserInfo
  },
  // 清空用户信息
  removeUserInfo(state) {
    state.UserInfo = {}
  }
}

const actions = {
  // 登录
  async login(context, data) {
    const res = await reqLogin(data)
    context.commit('getToken', res.data)
  },
  // 获取数据
  async setUserInfo(context) {
    const { data: res1 } = await reqGetUserInfo()
    const { data: res2 } = await reqGetUserDetailById(res1.userId)
    const res = { ...res1, ...res2 }
    context.commit('getUserInfo', res)

    return res
  },
  // 退出
  logout(context) {
    // 1.清除token
    context.commit('removeToken')
    // 2.移除vuex个人信息
    context.commit('removeUserInfo')
    // 3.重置路由
    resetRouter()
    // 4. 重置 vuex 中的路由信息
    context.commit('permission/setRoutes', [], { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

